<template>
  <el-dialog
    :title="isEdit ? '编辑公告' : '发布公告'"
    v-model="dialogVisible"
    width="70%"
    :before-close="handleClose"
  >
    <el-form :model="form" ref="formRef" :rules="rules" label-width="100px">
      <el-form-item label="站点" prop="siteId">
        <el-select v-model="form.siteId" placeholder="请选择站点">
          <el-option
            v-for="site in siteOptions"
            :key="site.id"
            :label="site.siteName"
            :value="site.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入标题" />
      </el-form-item>

      <el-form-item label="内容" prop="content">
        <RichTextEditor v-model="form.content" />
      </el-form-item>

      <el-form-item label="置顶">
        <el-radio-group v-model="form.top">
          <el-radio :label="0">是</el-radio>
          <el-radio :label="1">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="附件">
        <input 
          type="file" 
          ref="fileInput" 
          style="display: none" 
          @change="handleFileChange"
        >
        <el-button type="primary" @click="triggerFileInput">选择文件</el-button>
        <span v-if="form.attachmentName" class="file-name">
          <el-link 
            :href="form.attachment" 
            type="primary" 
            :underline="false"
            target="_blank"
          >
            {{ form.attachmentName }}
          </el-link>
          <el-button type="danger" link @click="removeFile">

          </el-button>
        </span>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import RichTextEditor from './RichTextEditor.vue'
import { ElMessage } from 'element-plus'
import { Document, Delete } from '@element-plus/icons-vue'
import axios from '../plugins/axios'
import { config } from '../config'

const props = defineProps({
  visible: Boolean,
  editData: Object,
  isEdit: Boolean,
  siteOptions: Array
})

const emit = defineEmits(['update:visible', 'onSubmit'])

const dialogVisible = ref(false)
const formRef = ref(null)

// 添加上传相关的响应式变量
const isUploading = ref(false)
const uploadProgress = ref(0)
const uploadStatus = ref('')

// 添加文件输入引用
const fileInput = ref(null)

// 修改表单数据，添加 top 字段
const form = ref({
  siteId: '',
  title: '',
  content: '',
  attachment: '',
  attachmentName: '',
  top: 0// 默认不置顶
})

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value.click()
}

// 处理文件选择
const handleFileChange = async (event) => {
  const file = event.target.files[0]
  if (file) {
    const formData = new FormData()
    formData.append('file', file)
    
    try {
      const response = await axios.post('/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      
      if (response.data.code === 1) {
        form.value.attachment = response.data.data.filePath
        form.value.attachmentName = response.data.data.fileName
        ElMessage.success('文件上传成功')
      } else {
        ElMessage.error(response.data.msg || '文件上传失败')
      }
    } catch (error) {
      console.error('文件上传失败:', error)
      ElMessage.error('文件上传失败')
    }
  }
}

// 修改提交方法，直接提交表单数据
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    const valid = await formRef.value.validate()
    if (valid) {
      const url = props.isEdit ? '/public/update' : '/public/save'
      const response = await axios.post(url, form.value)
      
      if (response.data.code === 1) {
        ElMessage.success(props.isEdit ? '编辑成功' : '发布成功')
        emit('onSubmit')
        dialogVisible.value = false
      } else {
        ElMessage.error(response.data.msg || '操作失败')
      }
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

const rules = {
  siteId: [{ required: true, message: '请选择站点', trigger: 'change' }],
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
}

// 监听visible属性变化
watch(() => props.visible, (val) => {
  dialogVisible.value = val
})

// 监听 editData 变化，实现数据回显
watch(() => props.editData, (newVal) => {
  if (newVal) {
    form.value = {
      siteId: newVal.siteId,
      title: newVal.title,
      content: newVal.content,
      attachment: newVal.attachment || '',
      attachmentName: newVal.attachmentName || '',
      top: newVal.top || 0,
      id: newVal.id
    }
  } else {
    // 清空表单
    form.value = {
      siteId: '',
      title: '',
      content: '',
      attachment: '',
      attachmentName: '',
      top: 0
    }
  }
}, { immediate: true })

// 修改 dialogVisible 监听，增加重置逻辑
watch(dialogVisible, (val) => {
  emit('update:visible', val)
  if (!val && !props.isEdit) {
    // 只有在非编辑模式下才重置表单
    formRef.value?.resetFields()
  }
})

// 处理关闭
const handleClose = () => {
  dialogVisible.value = false
}

</script>

<style scoped>
.dialog-footer {
  padding: 20px 0 0;
  text-align: right;
}

.uploaded-file {
  margin-top: 10px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.file-name {
  margin-left: 10px;
  font-size: 14px;
}
</style>